﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Domino;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Xml.Serialization;
using System.Collections.Specialized;

namespace NotesCommonProjects
{

    public partial class ShowAllNotesDocumentItemsValue : System.Web.UI.Page
    {
        //宣告Notes物件
        //總務用品申請單
        public NotesSession session;
        public NotesDatabase db;
        public NotesView view;
        public NotesView stationery_1_view;
        public NotesDocument temp_doc;
        public NotesDocument stationery_doc;
        public NotesDocument robot_doc;
        public NotesDocument new_doc;
        public NotesDocument first_doc_for_debug;
        public NotesDocumentCollection all_doc;
        public NotesItem item;

        //參考資料庫
        public NotesDatabase refe0_db;
        public NotesView id_view;
        public NotesDocument refe_doc;

        //簽核流程
        public NotesDatabase sapproval_db;
        public NotesView approve_key_view;
        public NotesDocument approve_doc;

        //宣告機器人丟來的資料
        //public string user_name_from_robot = "黃鴻仁";
        public string pps_code = "23204";
        public string user_name_from_robot = null;
        public string supply_category = "TKEYWORD=GIFTS";
        public string supply_item = "TSUBTYPE=贈禮品&TNAME=烏魚子&TSPEC=單一規格";
        //public string supply_category = "tType=文具用品";
        //public string supply_item = "tSubType=筆類&tName=筆心&tSpec=自動鉛筆心";
        public string supply_amount = "NQTY=3";
        public string robot_remark = "從iSender總務用品申請機器人 申請";

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {

                Type NotesType = Type.GetTypeFromProgID("Notes.NotesSession");
                dynamic Session = Activator.CreateInstance(NotesType);

                //建立NotesSession
                session = new NotesSession();

                //Initialize方法會自動抓目前系統登入使用的Notes id檔, 並要求輸入密碼
                session.Initialize("kizuki33");

                //取得指定位置的NotesDatabase
                db = session.GetDatabase("TNOTES01/T/CCP", "Stationery.NSF", false);//總務用品申請單

                //取得指定的NotesView
                view = db.GetView("vStatus");

                //取得所有文件
                temp_doc = view.GetFirstDocument();
                first_doc_for_debug = view.GetFirstDocument();
                while (temp_doc != null)
                {
                    //找尋機器人範本文件
                    var v = temp_doc.GetItemValue("CNS_Requestor");
                    if (v[0] == NotesCF.SampleDocumnetRequester)
                    {
                        robot_doc = temp_doc;
                        break;
                    }
                    else
                    {
                        temp_doc = view.GetNextDocument(temp_doc);
                    }
                }

                //儲存機器人範本文件物件至XML檔案中(失敗:無法序列化COM類)
                /*
                Stream fs = File.Create("C:\\RobotNotesDocument.bin");
                BinaryFormatter serializer = new BinaryFormatter();
                object temp_obj = (object)SerializableClass.SerializableObject(robot_doc);
                object[] obj_array = temp_doc.Items;
                serializer.Serialize(fs, obj_array);
                fs.Close();
                 */

                //取得呼叫服務者的中文名稱
                user_name_from_robot = GetChineseName(pps_code, true);

                if (user_name_from_robot != "")
                {

                    //建立新的空白文件
                    new_doc = db.CreateDocument();

                    //複製範本文件所有NotesItem到新文件(值也會複製過去)
                    robot_doc.CopyAllItems(new_doc, true);

                    //執行Postopen事件
                    Postopen();

                    //初始化欄位預設值
                    InitializeColumns();

                    //計算表單內的"計算欄位"和"寫作時計算欄位"
                    ComputeCaculatedColumns();

                    //帶入Web Service傳來的參數
                    EditColumns();

                    //執行寄送申請單事件
                    SendRequest();

                    //執行轉譯欄位程式碼
                    TranslateColumns();

                    //顯示所有欄位內容
                    ShowItemsValue(new_doc, robot_doc);
                    //ShowItemsValue(new_doc, first_doc_for_debug);

                    //計算此文件是否符合規範
                    if (new_doc.ComputeWithForm(false, false))
                    {
                        //new_doc.Save(true, true);    //將文件存入資料庫
                    }
                }
                else
                {
                    Response.Write("PPS_CODE:" + pps_code + " has no chinese name in the refe0 database.");
                }
            }
            catch (Exception ex)
            {
                Response.Write(ex.ToString());
                //總務用品申請單添加失敗
            }
        }
        public void Postopen()
        {
            //Formula
            //ERequestor_A : @UserName
            //Author_A : @UserName
            ////@UserName = CH Chou/MI/T/CCP                  ↓
            ////@DbLookup("";"DNOTES01":"refe0.nsf";"ID";"CH Chou/MI/T/CCP";5) = 周正欣

            //C#
            new_doc.GetFirstItem("ERequestor_A").Values = GetID(user_name_from_robot);
            new_doc.GetFirstItem("Author_A").Values = GetID(user_name_from_robot);

            //LotusScript
            //doc.tRequestor=Evaluate("@Name([CN];ERequestor_A)",doc)

            //C#
            new_doc.GetFirstItem("tRequestor").Values = GetEnglishName(GetID(user_name_from_robot));

            //LotusScript
            //doc.tFactory=docS.Unit1   '廠別
            //doc.tDept=docS.Unit2  '部門別
            //doc.tDivision=docS.Unit3  '課別

            //C#
            new_doc.GetFirstItem("tFactory").Values = refe_doc.GetItemValue("Unit1")[0];
            new_doc.GetFirstItem("tDept").Values = refe_doc.GetItemValue("Unit2")[0];
            new_doc.GetFirstItem("tDivision").Values = refe_doc.GetItemValue("Unit3")[0];

            //LotusSctipt
            //GET 總務用品系統承辦人之 UserName 及 流程(Flow) 總階段數
            //Set db2= New NotesDatabase(db.server,"SAPPROVAL.NSF")
            //Set view=db2.getview("Approve_Key_View")
            //viewkey=doc.SystemName(0) & doc.tFactory(0) & doc.tDept(0) & doc.tDivision(0) & "發送"
            //Set doc2=view.GetDocumentByKey(viewkey)

            //C#
            sapproval_db = session.GetDatabase("TNOTES01/T/CCP", "SAPPROVAL.NSF", false);
            approve_key_view = sapproval_db.GetView("Approve_Key_View");
            temp_doc = null;
            approve_doc = null;
            string viewkey = new_doc.GetItemValue("SystemName")[0] + new_doc.GetItemValue("tFactory")[0] +
                new_doc.GetItemValue("tDept")[0] + new_doc.GetItemValue("tDivision")[0] + "發送";
            approve_doc = approve_key_view.GetDocumentByKey(viewkey);


            //LotusScript
            //doc.tFlowNo = doc2.tStatus(0)
            //doc.Handler=doc2.aUsername
            //zz=doc2.altUsername		
            //Set item = doc.GetFirstItem( "tHandler" )
            //Call item.AppendToTextList(doc.Handler) 
            //Call item.AppendToTextList(zz) 
            //doc.tHandler= Evaluate("@unique(tHandler)", doc)		
            //doc.tStatusCode=doc2.tStatus	

            //C#
            new_doc.GetFirstItem("tFlowNo").Values = approve_doc.GetItemValue("tStatus")[0];
            new_doc.GetFirstItem("Handler").Values = approve_doc.GetItemValue("aUserName")[0];
            new_doc.GetFirstItem("tHandler").AppendToTextList(new_doc.GetItemValue("Handler")[0]);
            new_doc.GetFirstItem("tHandler").AppendToTextList(approve_doc.GetItemValue("altUsername")[0]);
            new_doc.GetFirstItem("tHandler").Values = session.Evaluate("@unique(tHandler)", new_doc);
            new_doc.GetFirstItem("tStatusCode").Values = approve_doc.GetItemValue("tStatus")[0];
        }
        public void InitializeColumns()
        {
            //有初值的可編輯欄位們
            //隱藏欄位
            new_doc.GetFirstItem("tStatusCode").Values = "1";
            new_doc.GetFirstItem("IsProcessed").Values = "0";
            new_doc.GetFirstItem("IsPurchased").Values = "0";
            new_doc.GetFirstItem("MailFlag").Values = "初始狀態";

            //表單欄位
            new_doc.GetFirstItem("Status").Values = "寫作中";
            new_doc.GetFirstItem("tKeyWord").Values = "Stationery";
            for (int i = 1; i <= 11; i++)
            {
                new_doc.GetFirstItem("nQty" + i.ToString()).Values = "0";
                new_doc.GetFirstItem("tUser" + i.ToString()).Values = user_name_from_robot;
            }
            new_doc.GetFirstItem("TotalPrice").Values = "0";
            //new_doc.GetFirstItem("XMLText").Values = "";
            new_doc.ReplaceItemValue("XMLText", "");
            new_doc.GetFirstItem("tFlag").Values = "";
            new_doc.GetFirstItem("Form").Values = "RequestForm";
        }
        public void ComputeCaculatedColumns()
        {
            //計算欄位們
            //隱藏欄位
            new_doc.GetFirstItem("SystemName").Values = "總務用品申請單";
            new_doc.GetFirstItem("ERequestor_A").Values = GetID(user_name_from_robot);
            new_doc.GetFirstItem("Author_A").Values = GetID(user_name_from_robot);

            //節省偵錯時間 可先註解掉
            new_doc.GetFirstItem("tApproveNextCNSName").Values = GetChineseName(new_doc.GetItemValue("ApproveNext")[0]);
            new_doc.GetFirstItem("tRejectToCNSName").Values = GetChineseName(new_doc.GetItemValue("RejectTo")[0]);
            new_doc.GetFirstItem("tHandlerCNSName").Values = GetChineseName(new_doc.GetItemValue("Handler")[0]);

            new_doc.GetFirstItem("ProcessedTime").Values = session.Evaluate("@Now", new_doc);

            //奇怪找不到此Item        ↓↓
            //new_doc.GetFirstItem("xKeyWord").Values = new_doc.GetItemValue("tKeyWord")[0] + "_1";
            //new_doc.GetFirstItem("UN").Values = GetEnglishName(GetID(user_name_from_robot));

            new_doc.GetFirstItem("CNS_UN").Values = user_name_from_robot;

            //表單欄位
            new_doc.GetFirstItem("CNS_Requestor").Values = user_name_from_robot;
            new_doc.GetFirstItem("dDate").Values = session.Evaluate("@Now", new_doc);
            new_doc.GetFirstItem("CRequestor").Values = GetEnglishName(GetID(user_name_from_robot));

            //奇怪找不到此Item        ↓↓
            //new_doc.GetFirstItem("Xserialno").Values = new_doc.GetItemValue("serialno")[0];

            new_doc.GetFirstItem("dDate").Values = session.Evaluate("@Now", new_doc);

            for (int i = 1; i <= 11; i++)
            {
                new_doc.GetFirstItem("tUnit" + i.ToString()).Values = GetUnitName(
                    new_doc.GetItemValue("tKeyWord")[0] + "_1",
                    new_doc.GetItemValue("tName" + i.ToString())[0]);
            }
            new_doc.ReplaceItemValue("xProcDate", "");
            new_doc.ReplaceItemValue("xProcTime", "");
            new_doc.ReplaceItemValue("xProcName", "");
            new_doc.ReplaceItemValue("xProcAct", "");
            new_doc.GetFirstItem("xApprove_Opinion").Values = new_doc.GetItemValue("CNS_UN")[0] +
                session.Evaluate("@Now", new_doc)[0] + new_doc.GetItemValue("tApprove_Opinion")[0] +
                "  ------ 填寫申請單";
        }
        public void EditColumns()
        {
            /*
             public string user_name_from_robot = "周正欣";
             public string supply_category = "tKeyWord=贈禮品";
             public string supply_item = "tSubType=贈禮品&tName=烏魚子&tSpec=單一規格";
             //public string supply_category = "tType=文具用品";
             //public string supply_item = "tSubType=筆類&tName=筆心&tSpec=自動鉛筆心";
             public string supply_amount = "nQty=2";
             public string robot_remark = "從iSender總務用品申請機器人 申請";
             */

            NameValueCollection supply_category_query_string = HttpUtility.ParseQueryString(supply_category);
            NameValueCollection supply_item_query_string = HttpUtility.ParseQueryString(supply_item);
            NameValueCollection supply_amount_query_string = HttpUtility.ParseQueryString(supply_amount);

            string temp = supply_category_query_string.GetValues("tKeyWord")[0];

            new_doc.GetFirstItem("tKeyWord").Values = temp;

            /*
             @If(tKeyWord="Stationery";"文具用品";
             * tKeyWord="Mags";"書籍雜誌";
             * tKeyWord="Gifts";"贈禮品";
             * tKeyWord="Elecs";"電器零件";
             * tKeyWord="Misc";"其他";
             * tKeyWord="Print";"印刷品";"")
             */

            switch (temp)
            {
                case "STATIONERY":
                    temp = "文具用品";
                    break;
                case "MAGS":
                    temp = "書籍雜誌";
                    break;
                case "GIFTS":
                    temp = "贈禮品";
                    break;
                case "ELECS":
                    temp = "電器零件";
                    break;
                case "MISC":
                    temp = "其他";
                    break;
                case "PRINT":
                    temp = "印刷品";
                    break;
            }

            new_doc.ReplaceItemValue("tType", temp);

            new_doc.GetFirstItem("tSubType1").Values = supply_item_query_string.GetValues("tSubType");
            new_doc.GetFirstItem("tName1").Values = supply_item_query_string.GetValues("tName");
            new_doc.GetFirstItem("tSpec1").Values = supply_item_query_string.GetValues("tSpec");
            new_doc.GetFirstItem("nQty1").Values = supply_amount_query_string.GetValues("nQty");
            new_doc.GetFirstItem("rRemark1").Values = robot_remark;
        }
        public void SendRequest()
        {
            //LotusScript
            //doc.tStatusCode="2"
            //Set db2= New NotesDatabase(db.server,"SAPPROVAL.NSF")
            //Set view1=db2.getview("Approve_Status_View")
            //viewkey=doc.SystemName(0) & doc.tFactory(0) & doc.tDept(0) & doc.tDivision(0) & doc.tStatusCode(0)


            //C#
            new_doc.GetFirstItem("tStatusCode").Values = "2";
            NotesView approve_status_view = sapproval_db.GetView("Approve_Status_View");
            string viewkey = new_doc.GetItemValue("SystemName")[0] + new_doc.GetItemValue("tFactory")[0] +
                new_doc.GetItemValue("tDept")[0] + new_doc.GetItemValue("tDivision")[0] +
                new_doc.GetItemValue("tStatusCode")[0];


            //LotusScript
            //Set doc3=view1.GetDocumentByKey(viewkey)
            //Set doc4=view1.GetNextDocument(doc3)

            //C#
            NotesDocument approve_next_doc = approve_status_view.GetDocumentByKey(viewkey);
            NotesDocument next_approve_next_doc = approve_status_view.GetNextDocument(approve_next_doc);

            //LotusScript
            //doc.ApproveNext=doc3.aUsername
            //doc.tApproveNext=Evaluate("@Name([CN];ApproveNext)",doc)
            //doc.WhoCheck=doc.tApproveNext

            //C#
            new_doc.GetFirstItem("ApproveNext").Values = approve_next_doc.GetItemValue("aUsername")[0];
            new_doc.GetFirstItem("tApproveNext").Values = session.Evaluate("@Name([CN];ApproveNext)", new_doc);
            new_doc.GetFirstItem("WhoCheck").Values = new_doc.GetItemValue("tApproveNext")[0];

            //LotusScript
            //Call uidoc.refresh

            //C#
            ComputeCaculatedColumns();

            //LotusScript
            //Set emaildoc=New NotesDocument(db)
            //Set rtitem=New NotesRichTextItem(emaildoc, "Body")
            //emaildoc.SendTo=doc.ApproveNext(0)
            //emaildoc.subject="請簽核" & doc.CNS_Requestor(0) & "之總務用品申請單 !!"


            //C#
            NotesDocument email_doc = db.CreateDocument();
            NotesRichTextItem rich_text_item = email_doc.CreateRichTextItem("Body");
            email_doc.ReplaceItemValue("SendTo", new_doc.GetItemValue("ApproveNext")[0]);
            email_doc.ReplaceItemValue("Subject", "請簽核" +
                new_doc.GetItemValue("CNS_Requestor")[0] + "之總務用品申請單 !!");

            //LotusScript
            //doc.Status="簽核中"
            //doc.tStatusCode="2"
            //doc.tStatusCode_Next="3"
            //doc.tStatusCode_Prev="1"
            //doc.ProcessedTime=Now()
            //doc.xApprove_Opinion=doc.xApprove_Opinion(0) & Chr(13) & doc.CNS_UN(0) & Now() & "    送簽" 
            //doc.tApprove_Opinion=""

            //C#
            new_doc.GetFirstItem("Status").Values = "簽核中";
            new_doc.GetFirstItem("tStatusCode").Values = "2";
            new_doc.GetFirstItem("tStatusCode_Next").Values = "3";
            new_doc.GetFirstItem("tStatusCode_Prev").Values = "1";
            new_doc.GetFirstItem("ProcessedTime").Values = session.Evaluate("@Now", new_doc);
            new_doc.GetFirstItem("xApprove_Opinion").Values = new_doc.GetItemValue("xApprove_Opinion")[0] +
                "\r" + new_doc.GetItemValue("CNS_UN")[0] + session.Evaluate("@Now", new_doc)[0] + "    送簽";
            new_doc.GetFirstItem("tApprove_Opinion").Values = "";

            //LotusScript
            //doc.xProcName=doc.xProcName(0) & doc.CNS_UN(0) & Chr(13)
            //doc.xProcDate=doc.xProcDate(0) & ServerDate() & Chr(13) 
            //doc.xProcTime=doc.xProcTime(0) & ServerTime() & Chr(13)
            //doc.xProcAct=doc.xProcAct(0) & "寄送申請單" & Chr(13)
            //doc.Author_A=doc.ApproveNext

            //C#
            new_doc.GetFirstItem("xProcName").Values = new_doc.GetItemValue("xProcName")[0] +
                new_doc.GetItemValue("CNS_UN")[0] + "\r";
            new_doc.GetFirstItem("xProcDate").Values = new_doc.GetItemValue("xProcDate")[0] +
                DateTime.Now.ToShortDateString() + "\r";
            new_doc.GetFirstItem("xProcTime").Values = new_doc.GetItemValue("xProcTime")[0] +
                DateTime.Now.ToString("HH:mm:ss tt") + "\r";
            new_doc.GetFirstItem("xProcAct").Values = new_doc.GetItemValue("xProcAct")[0] +
                "寄送申請單" + "\r";
            new_doc.GetFirstItem("Author_A").Values = new_doc.GetItemValue("ApproveNext")[0];

            //LotusScript
            //Call rtitem.AppendText("請連續按二下滑鼠或以空白鍵開啟文件查看總務用品申請單 !!")
            //Call rtitem.AddNewLine(1)
            //Call rtitem.AppendDocLink(doc, "連結至文件")
            //Call doc.save(True,True)
            //Call emaildoc.Send(False)
            //Call uidoc.save
            //Call uidoc.close

            //C#
            rich_text_item.AppendText("請連續按二下滑鼠或以空白鍵開啟文件查看總務用品申請單 !!");
            rich_text_item.AddNewLine(1);
            rich_text_item.AppendDocLink(new_doc, "連結至文件");

            //執行就存檔了!!
            //new_doc.Save(true, true);

            email_doc.ReplaceItemValue("SendTo", "CH Chou/MI/T/CCP");
            //執行就寄出了!!
            //email_doc.Send(false);
        }
        public void TranslateColumns()
        {
            /*
             FIELD tNameSpecQty := tNameSpecQty;
             NSQ1:=tName1+";"+tSpec1+";"+@Text(nQty1);
             NSQ2:=tName2+";"+tSpec2+";"+@Text(nQty2);
             NSQ3:=tName3+";"+tSpec3+";"+@Text(nQty3);
             NSQ4:=tName4+";"+tSpec4+";"+@Text(nQty4);
             NSQ5:=tName5+";"+tSpec5+";"+@Text(nQty5);
             NSQ6:=tName6+";"+tSpec6+";"+@Text(nQty6);
             NSQ7:=tName7+";"+tSpec7+";"+@Text(nQty7);
             NSQ8:=tName8+";"+tSpec8+";"+@Text(nQty8);
             NSQ9:=tName9+";"+tSpec9+";"+@Text(nQty9);
             NSQ10:=tName10+";"+tSpec10+";"+@Text(nQty10);
             NSQ:=NSQ1+":"+NSQ2+":"+NSQ3+":"+NSQ4+":"+NSQ5+":"+NSQ6+":"+NSQ7+":"+NSQ8+":"+NSQ9+":"+NSQ10+":";
             @SetField("tNameSpecQty"; NSQ)
            */

            string NSQ = null;
            for (int i = 1; i <= 10; i++)
            {
                NSQ += new_doc.GetItemValue("tName" + i.ToString())[0] + ";" +
                    new_doc.GetItemValue("tSpec" + i.ToString())[0] + ";" +
                    new_doc.GetItemValue("nQty" + i.ToString())[0] + ":";
            }
            new_doc.GetFirstItem("tNameSpecQty").Values = NSQ;
        }

        //印出所有Item Value來看
        public void ShowItemsValue(NotesDocument doc1, NotesDocument doc2)
        {
            int temp = 0;
            string br = "</BR>";
            try
            {
                for (int i = 0; i < 256; i++)
                {
                    if (doc1.Items[i].Values[0] != null && doc2.Items[i].Values[0] != null && doc1.Items[i].Name != null && doc2.Items[i].Name != null)
                    {
                        Label1.Text += "<strong>" + doc1.Items[i].Name.ToString() +
                               "</strong> : " + doc1.Items[i].Values[0].ToString() +
                               "<span class=\"style2\"><strong> \\ </strong></span>" +
                               doc2.Items[i].Values[0].ToString() +
                               "<strong> : " + doc2.Items[i].Name.ToString() +
                               "</strong>" + br + br;
                        temp = i;
                    }
                }
            }
            catch (Exception ex)
            {
            }
        }

        //轉換名字functions
        public string GetChineseName(string english_name)
        {
            if (english_name == null || english_name == "")
            {
                return "";
            }
            else
            {
                refe0_db = session.GetDatabase("TNOTES01/T/CCP", "Refe0.NSF", false);
                id_view = refe0_db.GetView("ID");
                temp_doc = id_view.GetFirstDocument();
                refe_doc = null;
                while (temp_doc != null)
                {
                    string v = temp_doc.GetItemValue("ID")[0];
                    if (v == english_name)
                    {
                        refe_doc = temp_doc;
                        break;
                    }
                    else
                    {
                        temp_doc = id_view.GetNextDocument(temp_doc);
                    }
                    //找不到中文名的話
                    //寫在這裡
                }
                if (refe_doc == null)
                    return "";
                else if (refe_doc.GetItemValue("Name")[0] == null)
                    return "";
                else
                    return refe_doc.GetItemValue("Name")[0];
            }
        }
        public string GetChineseName(string pps_code, bool b)
        {
            if (pps_code == null || pps_code == "")
            {
                return "";
            }
            else
            {
                refe0_db = session.GetDatabase("TNOTES01/T/CCP", "Refe0.NSF", false);
                id_view = refe0_db.GetView("ID");
                temp_doc = id_view.GetFirstDocument();
                refe_doc = null;
                while (temp_doc != null)
                {
                    string v = temp_doc.GetItemValue("staffnu")[0];
                    if (v == pps_code)
                    {
                        refe_doc = temp_doc;
                        break;
                    }
                    else
                    {
                        temp_doc = id_view.GetNextDocument(temp_doc);
                    }
                    //找不到中文名的話
                    //寫在這裡
                }
                if (refe_doc == null)
                    return "";
                else if (refe_doc.GetItemValue("Name")[0] == null)
                    return "";
                else
                    return refe_doc.GetItemValue("Name")[0];
            }
        }
        public string GetID(string chinese_name)
        {
            refe0_db = session.GetDatabase("TNOTES01/T/CCP", "Refe0.NSF", false);
            id_view = refe0_db.GetView("ID");
            temp_doc = id_view.GetFirstDocument();
            refe_doc = null;
            while (temp_doc != null)
            {
                string v = temp_doc.GetItemValue("Name")[0];
                if (v == chinese_name)
                {
                    refe_doc = temp_doc;
                    break;
                }
                else
                {
                    temp_doc = id_view.GetNextDocument(temp_doc);
                }
                //找不到英文名的話
                //寫在這裡
            }
            if (refe_doc == null)
                return "";
            else if (refe_doc.GetItemValue("ID")[0] == null)
                return "";
            else
                return refe_doc.GetItemValue("ID")[0];
        }
        public string GetEnglishName(string id)
        {
            int start_index = id.IndexOf("CN=") + 3;
            int end_index = id.IndexOf("/");
            string english_name = id.Substring(start_index, end_index - start_index);

            if (english_name != null)
                return english_name;
            else
                return "";
        }

        //取得單位functions
        public string GetUnitName(string keyword, string t_name)
        {
            db = session.GetDatabase("TNOTES01/T/CCP", "Stationery.NSF", false);//總務用品申請單
            stationery_1_view = db.GetView(keyword);
            temp_doc = stationery_1_view.GetFirstDocument();
            stationery_doc = null;
            while (temp_doc != null)
            {
                string v = temp_doc.GetItemValue("tName")[0];
                if (v == t_name)
                {
                    stationery_doc = temp_doc;
                    break;
                }
                else
                {
                    temp_doc = stationery_1_view.GetNextDocument(temp_doc);
                }
                //找不到中文名的話
                //寫在這裡
            }
            if (stationery_doc == null)
                return "";
            else if (stationery_doc.GetItemValue("tUnit")[0] == null)
                return "";
            else
                return stationery_doc.GetItemValue("tUnit")[0];
        }

        //刪除上一筆文件
        protected void Button1_Click(object sender, EventArgs e)
        {
            string log_dir = NotesCF.StationeryLogDir;
            string FileName = DateTime.Now.ToString("yyyy_MM_dd") + ".txt";
            string user_name_from_robot = "周正欣";

            //1. 用user_name_from_robot到log檔中找出 使用者的最新一筆log中的 Notes文件處理時間
            FileStream fs = new FileStream(log_dir + FileName, FileMode.Open, FileAccess.Read);
            StreamReader sr = new StreamReader(fs);
            string LogContext = sr.ReadToEnd();

            int LastNameIndex = LogContext.LastIndexOf(user_name_from_robot);
            LogContext = LogContext.Substring(LastNameIndex);

            int NotesProcessedTimeIndex = LogContext.IndexOf("Notes文件處理時間：") + "Notes文件處理時間：".Length;
            string NotesProcessedTime = LogContext.Substring(NotesProcessedTimeIndex, LogContext.LastIndexOf("】") - NotesProcessedTimeIndex);

            //2. 用user_name_from_robot和Notes文件處理時間到 Stationery.NSF中找符合的文件 刪掉
            db = session.GetDatabase(NotesCF.TNotes01, NotesCF.StationeryDatabase, false);
            view = db.GetView("vStatus");
            temp_doc = view.GetFirstDocument();
            stationery_doc = null;
            while (temp_doc != null)
            {
                string v = temp_doc.GetItemValue("ProcessedTime")[0].ToString();
                string w = temp_doc.GetItemValue("CNS_Requestor")[0];
                if (v == NotesProcessedTime && w == user_name_from_robot)
                {
                    stationery_doc = temp_doc;
                    break;
                }
                else
                {
                    temp_doc = view.GetNextDocument(temp_doc);
                }
                //找不到中文名的話
                //寫在這裡
            }

            //找到欲刪除的文件 > stationery_doc
            bool IsRemoveSuccess = false;

            if (stationery_doc != null)
            {
                IsRemoveSuccess = stationery_doc.Remove(true);

                if (IsRemoveSuccess)
                {
                    //撤銷上一筆申請成功
                    //FormUpload.RobotTextSend(pps_code, NotesCF.DeleteLastRequestSuccessMessage("", ""));

                    //寫入Log
                    string LogContext2 = "【撤銷成功】 【服務使用者：" + GetChineseName(pps_code, true)
                        + "】 【Notes文件處理時間：" + NotesProcessedTime + "】";
                    NotesCF.WriteLog(NotesCF.StationeryLogDir, LogContext2);
                }
                else
                {
                    //撤銷上一筆申請失敗
                }
            }
            else
            {
                //找不到使用者名稱&Notes文件使間符合的文件
            }
        }
    }
}